import { defineStore } from 'pinia'
// 接口
import { login, getUser, reqLogin } from '@/api/user'
// 类型
import type { loginData, ReturnLoginData, ReturnUser } from '@/api/user/type'
import { getStorage, removeStore, setStorage } from '@/utils/storage'
import { routerArray, asyncRoter, anyRouter } from '@/router/router'

import type { UserType } from './type'
// 导入通知提示
import router from '@/router'
// 深度拷贝方法
import { cloneDeep } from 'lodash'
// 路由权限设置
const filterRouter = function (asyncRoter: any, routers: any) {
    return asyncRoter.filter((item: any) => {
        if (routers.includes(item.name)) {
            if (item.children && item.children > 0) {
                item.children = filterRouter(item.children, routers)
            }
            return true
        }
    })
}
const useCounterStore = defineStore('useCounterStore', {
    state: (): UserType => ({
        token: getStorage('TOKEN'),
        routerArray,
        username: '',
        avatar: '',
        btns: [],
    }),
    actions: {
        // 登录获取token
        async userLogin(obj: loginData) {
            const data: ReturnLoginData = await login(obj)
            if (data.code === 200) {
                this.token = data.data
                setStorage('TOKEN', data.data)
                return 'ok'
            } else {
                return Promise.reject(new Error(data.data as string))
            }
        },
        // 获取用户信息
        async getUsers() {
            const data: ReturnUser = await getUser()
            if (data.code === 200) {
                this.username = data.data.name
                this.avatar = data.data.avatar
                this.btns = data.data.buttons
                // 异步路由权限筛选
                let useRouter = filterRouter(
                    cloneDeep(asyncRoter),
                    data.data.routes,
                )
                // 获取新的路由存储
                this.routerArray = [...routerArray, ...useRouter, anyRouter]
                // 路由注册
                ;[...useRouter, anyRouter].forEach((itemRouter: any) => {
                    router.addRoute(itemRouter)
                })
            } else {
                Promise.reject(new Error(data.message))
            }
        },
        // 退出登录
        async outLogin() {
            const data = await reqLogin()
            // 退出登录我们要清除用户信息和token 还要返回到登录页
            if (data.code === 200) {
                this.username = ''
                this.avatar = ''
                this.token = ''
                removeStore('TOKEN')
            } else {
                Promise.reject(new Error(data.message))
            }
        },
    },
    getters: {},
})

export default useCounterStore
